package com.cd2cd.code_app.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class FileUtil {

    private static final String FOLDER_PATH = "/code-manager";
    public static final String setting_path = FOLDER_PATH + "/application.properties";
    public static final String service_path = FOLDER_PATH + "/code_main.jar";

    public static boolean hasSetting() {
        return checkHasFile(getPath()+setting_path);
    }

    /**
     * 读取配置文件
     * @return
     * @throws Exception
     */
    public static JSONObject readSetting(InputStream inputStream) throws Exception {

        String res = IOUtils.toString(inputStream, "utf-8");
        String[] lines = res.split("\n");
        JSONObject resJson = new JSONObject();
        resJson.put("code", 0);
        for(String line: lines) {

            if(line.indexOf("spring.multisource.password") == 0) {
                String passwd = line.trim().split("=")[1];
                resJson.put("password", passwd);
            }

            if(line.indexOf("spring.multisource.username") == 0) {
                String username = line.trim().split("=")[1];
                resJson.put("username", username);
            }

            if(line.indexOf("spring.multisource.url") == 0) {
                String value = line.trim().split("=")[1];

                // jdbc:mysql://localhost:3306/{auto_code}?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull

                value = value.substring(0, value.indexOf("?"));
                String host = value.substring(value.indexOf("//")+2, value.lastIndexOf(":"));
                String port = value.substring(value.lastIndexOf(":")+1, value.lastIndexOf("/"));
                String database = value.substring(value.lastIndexOf("{")+1, value.lastIndexOf("}"));
                resJson.put("host", host);
                resJson.put("port", port);
                resJson.put("database", database);
            }
        }
        return resJson;
    }

    public static JSONObject readCustomerApplicationPro() throws Exception {
        return readSetting(new FileInputStream(new File(getPath()+setting_path)));
    }

    public static JSONObject readJarApplicationPro() throws Exception {
        String jarFile = getPath()+service_path; // FileUtil.class.getResource("/code_main.jar").getFile();
        InputStream input = loadResourceFromJarFile(jarFile, "BOOT-INF/classes/application.properties");
        return readSetting(input);
    }

    public static void saveCustomerApplicationPro(String host, String username, String password, int port, String database) throws IOException {
        String jarFile = getPath()+service_path;
        InputStream input = loadResourceFromJarFile(jarFile, "BOOT-INF/classes/application.properties");
        String res = IOUtils.toString(input, "utf-8");
        String[] lines = res.split("\n");
        StringBuilder content = new StringBuilder();
        for(String line: lines) {

            if(line.indexOf("spring.multisource.password") == 0) {
                content.append("spring.multisource.password=").append(password).append("\n");
                continue;
            }

            if(line.indexOf("spring.multisource.username") == 0) {
                content.append("spring.multisource.username=").append(username).append("\n");
                continue;
            }

            if(line.indexOf("spring.multisource.url") == 0) {
                content.append("spring.multisource.url=jdbc:mysql://").append(host)
                .append(":").append(port).append("/").append("{").append(database).append("}")
                .append("?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull").append("\n");
                continue;
            }
            content.append(line).append("\n");
        }
        File file = new File(getPath()+setting_path);
        if( ! file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        IOUtils.write(content.toString(), new FileOutputStream(file), "utf-8");
    }

    public static boolean hasCodeMain() {
        return checkHasFile(getPath()+service_path);
    }

    public static void copyCodeMain() throws Exception {
        if( ! hasCodeMain()) {
            File targetFile = new File(getPath()+service_path);

            InputStream inputStream = FileUtil.class.getResourceAsStream("/code_main.jar");
            IOUtils.copy(inputStream, new FileOutputStream(targetFile));
        }
    }

    private static boolean checkHasFile(String path) {
        File file = new File(path);

        if( ! file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }

        System.out.println("hasSetting="+file.getAbsolutePath());

        if(file.exists()) {
            return true;
        } else {
            return false;
        }
    }

    public static String getPath()
    {
        String path = FileUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        if(System.getProperty("os.name").contains("dows"))
        {
            path = path.substring(1);
        }
        if(path.contains("jar"))
        {
            path = path.substring(0,path.lastIndexOf("."));
            return path.substring(0,path.lastIndexOf("/"));
        }
        return path.replace("target/classes/", "");
    }

    public static InputStream loadResourceFromJarFile(String jarPath, String resPath) {
        if (!jarPath.endsWith(".jar")) {
            return null;
        }
        System.out.println(jarPath);
        try {
            JarFile jarFile = new JarFile(jarPath);
            JarEntry jarEntry = jarFile.getJarEntry(resPath);
            if (jarEntry == null) {
                return null;
            }
            return jarFile.getInputStream(jarEntry);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        String jarFile = FileUtil.class.getResource("/code_main.jar").getFile();

        System.out.println("jarFile=" + jarFile);

        InputStream input = loadResourceFromJarFile(jarFile, "BOOT-INF/classes/application.properties");
        System.out.println(IOUtils.toString(input, "utf-8"));
    }

}
